from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import document

import simplejson as json
import re
import urllib2

def OnBlipSubmitted(properties, context):
    blip = context.GetBlipById(properties['blipId'])
    m = re.match('\[(.+)\]', blip.GetDocument().GetText())
    doc = urllib2.urlopen('http://query.yahooapis.com/v1/public/yql?q='+urllib2.quote(m.group(1))+"&format=json&diagnostics=false&env=http%3A%2F%2Fdatatables.org%2Falltables.env")
    sub_blip = blip.CreateChild().GetDocument()
    parsed = json.load(doc)
    
    sub_blip.AppendText("\n\n")
    for result in parsed['query']['results']['result']:
        for key in result.keys():
            sub_blip.AppendText(key+":   "+result[key])
            sub_blip.AppendText("\n")
        sub_blip.AppendText("\n----------------------------------------------\n\n")
    
def OnRobotAdded(properties, context):
    context.GetRootWavelet().CreateBlip().GetDocument().SetText("YQL Bot is now in session. Enter query in [  ] to fetch results.")

if __name__ == '__main__':
  myRobot = robot.Robot('YQLBot',
      image_url='http://www.wavy-robot.appspot.com/assets/icon.png',
      version='2',
      profile_url='')
  myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmitted)
  myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
  myRobot.Run()
